package com.cloud.rou.im.protocol.serialize;

import com.cloud.rou.im.core.util.IOUtil;
import com.cloud.rou.im.core.util.ObjectNullUtil;
import com.sun.xml.internal.ws.util.UtilException;

import java.io.*;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 */
@BindAndEnableSerializer(name = SerializeTypeConstants.JDK)
public class JdkSerializer implements Serializer {

    private JdkSerializer() {

    }

    @Override
    public byte[] serialize(Object object) {
        ObjectNullUtil.notNull(object);
        if (object instanceof Serializable) {
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            ObjectOutputStream oos = null;
            try {
                oos = new ObjectOutputStream(byteOut);
                oos.writeObject(object);
                oos.flush();
            } catch (Exception var7) {
                throw new UtilException(var7);
            } finally {
                IOUtil.close(oos);
            }
            return byteOut.toByteArray();
        } else {
            return null;
        }
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        ObjectNullUtil.notNull(bytes);
        ObjectInputStream ois = null;
        try {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            ois = new ObjectInputStream(byteArrayInputStream);
            return (T) ois.readObject();
        } catch (Exception var3) {
            throw new UtilException(var3);
        }
    }


}
